package com.zebra.gateway;


import com.zebra.gateway.protocol.GatewayCodec;
import com.zebra.remoting.RemotingServer;
import com.zebra.remoting.ZebraRpcServer;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.config.GatewayServerInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class GatewayServerApplication {

    @Value("${spring.application.name}")
    private String appName;

    @Value("${zebra.port}")
    private int nettyPort;

    @Value("${zebra.weight}")
    private int weight;


    /**
     * 启动 仅仅启动tcp 服务器
     *
     * run tms server
     * @throws Exception
     */
    public void run(SourceProperties sourceProperties) throws Exception {

        if (nettyPort < 5000 || nettyPort > 65535){
            throw new Exception("port lg 5000 or gt 65535");
        }

        if (null == sourceProperties  || sourceProperties.isNull()){
            throw new Exception("SourceProperties is null");
        }


        GatewayServerInfo serverInfo = new GatewayServerInfo();
        serverInfo.setAppName(appName);
        serverInfo.setInIP(sourceProperties.getIpIn());
        serverInfo.setOutIP(sourceProperties.getIpOut());
        serverInfo.setPort(nettyPort);
        serverInfo.setWeight(weight);
        serverInfo.setInner(sourceProperties.getInner());

        RemotingServer server = new ZebraRpcServer();
        server.registerRpcCodec(new GatewayCodec());
        server.registerCommandHandler(new CommandServerHandler());
        if (!server.start(nettyPort)) {
            throw  new Exception("server start failure");
        }

        // start success serverInfo set mananger
        GwConfigInfoManager.getInstance().registerCMDS(BasisCommandCode.toListProfile());
        GwConfigInfoManager.getInstance().setGwServerInfo(serverInfo);
        GwConfigInfoManager.getInstance().setRegisterAddr(sourceProperties.getRegisterAddr());
        GwServerProcessorManager.getInstance().start(8, 20);
        GwClientProcessorManager.getInstance().start(8, 10);

    }



}
